//
//  SceneDelegate.m
//  ClockIn v2
//
//  Created by Tomy on 12/11/2020.
//

#import "SceneDelegate.h"
#import "AppDelegate.h"
#import "HomeViewDemo2.h"
#import "HomeViewDemo.h"
#import "GroundViewDemo.h"
#import "AFNetworking.h"
#import "StartViewController.h"
#import "Utility.h"


@interface SceneDelegate ()

// 个人数据库
@property(nonatomic, strong)NSString *selfID;
@property(nonatomic, strong)NSString *selfName;
@property (nonatomic, strong) NSMutableArray *selfNames;
@property (nonatomic, strong) NSMutableArray *selfDetail;
@property (nonatomic, strong) NSMutableArray *selfTag;
@property (nonatomic, strong) NSMutableArray *selfUserNames;
@property (nonatomic, strong) NSMutableArray *selfcontent;
@property (nonatomic, strong) NSMutableArray *selfLikeNum;
@property (nonatomic, strong) NSMutableArray *selfCommentNum;
@property (nonatomic, strong) NSMutableArray *selfTime;

// 本地数据库
@property (nonatomic, strong) NSDictionary *Dictionary;
@property (nonatomic, strong) NSMutableArray *arrDataID;
@property (nonatomic, strong) NSMutableArray *arrOwnID;
@property (nonatomic, strong) NSMutableArray *arrName;
@property (nonatomic, strong) NSMutableArray *arrDetail;
@property (nonatomic, strong) NSMutableArray *arrTag;
@property (nonatomic, strong) NSMutableArray *userName;
@property (nonatomic, strong) NSMutableArray<NSArray *> *imageURL;
@property (nonatomic, strong) NSMutableArray *arrLikeNum;
@property (nonatomic, strong) NSMutableArray *arrCommentNum;
@property (nonatomic, strong) NSMutableArray *arrTime;

// 内容合成（name+detail）
@property (nonatomic, strong) NSMutableArray *content;

@end

@implementation SceneDelegate


- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    
    self.window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];
    UIWindowScene *windowScene = (UIWindowScene*)scene;
    
    StartViewController *VC = [[StartViewController alloc] init];
    
    self.window.rootViewController = VC;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [self Login:@"dream@sysu.edu.cn" password: @"test"];

   
    
    // TabBar中的三个子页面

}

- (void) Login: (NSString *)name password:(NSString *)password{
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary *paramDict = @{
        @"name": name,
        @"password": password
    };
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
     
    [manager POST:@"http://172.18.178.56/api/user/login/pass" parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self getSelfInfo];
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //NSLog(@"error: %@", error);
     }];
}

- (void) getSelfInfo{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSDictionary *paramDict = @{
                                @"username":@"dandan",
                                @"pwd":@"dandan",
                                @"type":@"JSON"
                                };
    [manager GET:@"http://172.18.178.56/api/user/info/self" parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.selfID = responseObject[@"ID"];
        self.selfName = responseObject[@"Name"];
        [self getSelfContentText];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"请求失败--%@",error);
    }];
}

- (void) getSelfContentText{
    NSString *url = [NSString stringWithFormat:@"http://172.18.178.56/api/content/texts/%@", self.selfID];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSDictionary *paramDict = @{
                                @"username":@"dandan",
                                @"pwd":@"dandan",
                                @"type":@"JSON"
                                };
    [manager GET:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self AnalysiDictionary:responseObject];
        [self creatContent];
        [self getGround];
        [self creatView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"请求失败--%@",error);
    }];
}

- (void) AnalysiDictionary:(NSDictionary *)Dictionary{
    //NSLog(@"%@", [Dictionary[@"Data"]);
    NSArray * arr1 = Dictionary[@"Data"];
    self.selfNames = [NSMutableArray array];
    self.selfDetail = [NSMutableArray array];
    self.selfTag = [NSMutableArray array];
    self.selfUserNames = [NSMutableArray array];
    self.selfLikeNum = [NSMutableArray array];
    self.selfCommentNum = [NSMutableArray array];
    self.selfTime = [NSMutableArray array];
    for(NSDictionary * dic in arr1){
        [self.selfDetail addObject:dic[@"Detail"]];
        [self.selfNames addObject:dic[@"Name"]];
        [self.selfTag addObject:dic[@"Tag"]];
        [self.selfLikeNum addObject:dic[@"LikeNum"]];
        [self.selfCommentNum addObject:dic[@"CommentNum"]];
        [self.selfUserNames addObject:self.selfName];
        [self.selfTime addObject:dic[@"PublishDate"]];
    }
    NSLog(@"%@", self.selfCommentNum);
}

- (void) creatContent{
    self.selfcontent = [NSMutableArray array];
    for(int i = 0; i < [self.selfNames count]; i++){
        NSString *temp = [[NSString alloc]initWithFormat: @"%@\n%@", self.selfNames[i], self.selfDetail[i]];
        [self.selfcontent addObject: temp];
    }
}

- (void) getGround{
    // 请求获取公共内容
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *paramDict = @{
                                @"username":@"dandan",
                                @"pwd":@"dandan",
                                @"type":@"JSON"
                                };
    [manager GET:@"http://172.18.178.56/api/content/public?page=1&eachPage=0" parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [self AnalysiDictionary2:responseObject];
        [self creatContent2];
        [self creatView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"请求失败--%@",error);
    }];
}

- (void) AnalysiDictionary2:(NSDictionary *)Dictionary{
    //NSLog(@"%@", [Dictionary[@"Data"]);
    NSArray * arr1 = Dictionary[@"Data"];
    self.arrDataID = [NSMutableArray array];
    self.arrOwnID = [NSMutableArray array];
    self.arrName = [NSMutableArray array];
    self.arrTag = [NSMutableArray array];
    self.arrDetail = [NSMutableArray array];
    self.userName = [NSMutableArray array];
    self.imageURL = [NSMutableArray<NSArray *> array];
    self.arrLikeNum = [NSMutableArray array];
    self.arrCommentNum = [NSMutableArray array];
    self.arrTime = [NSMutableArray array];
    
    for(NSDictionary * dic in arr1){
        NSDictionary * dic2 = dic[@"Data"];
        [self.arrName addObject:dic2[@"Name"]];
        [self.arrDataID addObject: dic2[@"ID"]];
        [self.arrOwnID addObject: dic2[@"OwnID"]];
        [self.arrTag addObject: dic2[@"Tag"]];
        [self.arrDetail addObject: dic2[@"Detail"]];
        [self.arrLikeNum addObject: dic2[@"LikeNum"]];
        [self.arrCommentNum addObject: dic2[@"CommentNum"]];
        [self.arrTime addObject: dic2[@"PublishDate"]];
        NSDictionary * dic3 = dic[@"User"];
        [self.userName addObject: dic3[@"Name"]];
        NSDictionary * dic4 = dic2[@"Album"];
        NSArray * arr2 = dic4[@"Images"];
        NSMutableArray *imageURLS = [NSMutableArray array];
        for(NSDictionary * dic_i in arr2){
            //NSLog(@"%@", dic_i[@"Thumb"]);
            [imageURLS addObject: dic_i[@"Thumb"]];
        }
        [self.imageURL addObject:imageURLS];
        //NSLog(@"%@", self.imageURL);
    }
    //NSLog(@"Time %@", self.arrTime);
//    for(id i in self.imageURL){
//        NSLog(@"%@", i);
//    }
}

- (void) creatContent2{
    self.content = [NSMutableArray array];
    for(int i = 0; i < [self.arrDataID count]; i++){
        NSString *temp = [[NSString alloc]initWithFormat: @"%@\n%@", self.arrName[i], self.arrDetail[i]];
        [self.content addObject: temp];
    }
}

- (void) creatView{
    HomeViewDemo *homeView = [[HomeViewDemo alloc]init];
    
    [homeView InitData:self.selfcontent tagList:self.selfTag userName:self.selfUserNames image:nil LikeNum:self.selfLikeNum CommentNum:self.selfCommentNum Time:self.selfTime];
    GroundViewDemo *groundView = [[GroundViewDemo alloc]init];
    [groundView InitData:self.content tagList:self.arrTag userName:self.userName image:self.imageURL LikeNum:self.arrLikeNum CommentNum:self.arrCommentNum Time:self.arrTime ContentID:self.arrDataID UserID:self.arrOwnID];
    // 给三个页面设置导航栏
    UINavigationController *nav1 = [[UINavigationController alloc]initWithRootViewController:homeView];
    //[Utility     setTopBarWidth:nav1.navigationBar.frame.size.height + statusBarHeight];
    nav1.tabBarItem.title = @"主页";
    UINavigationController *nav2 = [[UINavigationController alloc]initWithRootViewController:groundView];
    nav2.tabBarItem.title = @"广场";
    UINavigationController *nav3 = [[UINavigationController alloc]initWithRootViewController:nil];
    nav3.tabBarItem.title = @"设置";

    // 导航栏设置Icon
    UIImage *img1 = [[UIImage imageNamed:@"home1.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    UIImage *img2 = [[UIImage imageNamed:@"home.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    UIImage *scaledImg1 = [self ImageZoom:img1];
    UIImage *scaledImg2 = [self ImageZoom:img2];
    nav1.tabBarItem.image = scaledImg1;
    nav1.tabBarItem.selectedImage = scaledImg2;
    
    img1 = [[UIImage imageNamed:@"note1.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    img2 = [[UIImage imageNamed:@"note.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    scaledImg1 = [self ImageZoom:img1];
    scaledImg2 = [self ImageZoom:img2];
    nav2.tabBarItem.image = scaledImg1;
    nav2.tabBarItem.selectedImage = scaledImg2;
    
    img1 = [[UIImage imageNamed:@"user1.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    img2 = [[UIImage imageNamed:@"user.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    scaledImg1 = [self ImageZoom:img1];
    scaledImg2 = [self ImageZoom:img2];
    nav3.tabBarItem.image = scaledImg1;
    nav3.tabBarItem.selectedImage = scaledImg2;

    UITabBarController *utbc = [[UITabBarController alloc]init];
    utbc.viewControllers = @[nav1, nav2, nav3];

    
    self.window.rootViewController = utbc;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
}

- (void)sceneDidDisconnect:(UIScene *)scene {
    // Called as the scene is being released by the system.
    // This occurs shortly after the scene enters the background, or when its session is discarded.
    // Release any resources associated with this scene that can be re-created the next time the scene connects.
    // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}


- (void)sceneDidBecomeActive:(UIScene *)scene {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}


- (void)sceneWillResignActive:(UIScene *)scene {
    // Called when the scene will move from an active state to an inactive state.
    // This may occur due to temporary interruptions (ex. an incoming phone call).
}


- (void)sceneWillEnterForeground:(UIScene *)scene {
    // Called as the scene transitions from the background to the foreground.
    // Use this method to undo the changes made on entering the background.
}


- (void)sceneDidEnterBackground:(UIScene *)scene {
    // Called as the scene transitions from the foreground to the background.
    // Use this method to save data, release shared resources, and store enough scene-specific state information
    // to restore the scene back to its current state.
}

- (UIImage *) ImageZoom:(UIImage *)image {
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * 0.18, image.size.height * 0.18));
    [image drawInRect:CGRectMake(0, 0, image.size.width * 0.18, image.size.height * 0.18)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

@end
